package com.example.demo.shrio;


import org.springframework.boot.web.servlet.ServletComponentScan;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Auther: mengxianwei
 * @Date: 2021/01/06/9:42 AM
 * @Description:添加过滤器，把所有请求过滤解决跨域问题
 */
@Component
@ServletComponentScan
@WebFilter(urlPatterns = "/*",filterName = "allFilter")
public class CorsFilter implements Filter {
    final static org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(CorsFilter.class);
    public void doFilter(ServletRequest req, ServletResponse res, FilterChain chain) throws IOException, ServletException {

        HttpServletResponse response = (HttpServletResponse) res;
        HttpServletRequest request = (HttpServletRequest) req;
        response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
        response.setHeader("Access-Control-Allow-Credentials", "true");
        response.setHeader("Access-Control-Allow-Methods", "*");
        response.setHeader("Access-Control-Allow-Headers", "Content-Type,Access-Token");//这里“Access-Token”是我要传到后台的内容key
        response.setHeader("Access-Control-Expose-Headers", "*");
        chain.doFilter(req, res);
    }
    public void init(FilterConfig filterConfig) {
    }

    public void destroy() {
    }
}
